package com.ljc.cjgl.controller;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

import org.abyss.data.specifications.Rule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ljc.cjgl.custom.TablePageable;
import com.ljc.cjgl.custom.TableResult;
import com.ljc.cjgl.entitiy.Teacher;
import com.ljc.cjgl.form.TeacherForm;
import com.ljc.cjgl.service.TeacherService;

@Controller
@RequestMapping(value="/teacher")
public class TeacherController {
	@Autowired
	private TeacherService service;
	
	@RequestMapping("/manage")
	public String manage() {
		return "teacher/manage";
	}
	
	@RequestMapping("/edit")
	public String edit(Integer id, ModelMap map) {
		Teacher teacher=new Teacher();
		if(id!=null) {
			teacher=service.findById(id);
		}
		map.put("model", teacher);
		return "teacher/edit";
	}
	
	@RequestMapping("/page")
	@ResponseBody
	public Object page(TablePageable pageable,TeacherForm form) {
		PageRequest pageRequest = pageable.bulidPageRequest();
		HashSet<Rule> rules=new HashSet<>();
		String name = form.getName();
		Integer userType = form.getUserType();
		String search = form.getSearch();
		if(StringUtils.hasText(name)) {
			rules.add(Rule.property("name").contain(name));
		}
		if(userType!=null) {
			rules.add(Rule.property("userType").equal(userType));
		}
		if(StringUtils.hasText(search)) {
			rules.add(Rule.property("name").contain(search));
		}
		Specification<Teacher> specification = Rule.and(rules).toSpecification();
		Page<Teacher> page=service.findAll(specification, pageRequest);
		return TableResult.bulidPageResult(page);
	}
	
	@RequestMapping("/save")
	@ResponseBody
	public Object save(TeacherForm form) {
		service.save(form);
		return TableResult.bulidResult(true, "数据保存成功");
	}
	
	@RequestMapping("/delete")
	@ResponseBody
	public Object delete(@RequestBody List<Teacher> teachers) {
		boolean success=service.delete(teachers);
		if(success) {
			return TableResult.bulidResult(true, "数据删除成功");
		}else {
			return TableResult.bulidResult(false, "数据删除失败");
		}
	}
}
